import { getGameState, sendBroadCast, getBoxesList, robBox, kbxRecharge, getMyBoxes } from '../../api/kbx/kbx';
import { wxPay } from '../../api/pay';
import { timeoutTask, getRandom, showWxToast, showWxLoading, hideWxLoading } from '../../utils/index';

const app = getApp();
const BX = [
    {
        num: '01',
        left: 129,
        top: 168,
    }, {
        num: '02',
        left: 281,
        top: 168,
    }, {
        num: '03',
        left: 444,
        top: 168,
    }, {
        num: '05',
        left: 62,
        top: 330,
    }, {
        num: '06',
        left: 213,
        top: 330,
    }, {
        num: '07',
        left: 365,
        top: 330,
    }, {
        num: '08',
        left: 521,
        top: 330,
    }, {
        num: '09',
        left: 37,
        top: 508,
    }, {
        num: '10',
        left: 201,
        top: 508,
    }, {
        num: '11',
        left: 364,
        top: 508,
    }, {
        num: '12',
        left: 521,
        top: 508,
    }, {
        num: '13',
        left: 42,
        top: 662,
    }, {
        num: '15',
        left: 206,
        top: 662,
    }, {
        num: '16',
        left: 360,
        top: 662,
    }, {
        num: '17',
        left: 526,
        top: 662,
    }, {
        num: '18',
        left: 117,
        top: 814,
    }, {
        num: '19',
        left: 279,
        top: 814,
    }, {
        num: '20',
        left: 444,
        top: 814,
    },
];
const giftList = [
    {
        id: 1,
        gift: 'rocket1',
        name: '小号火箭',
        imgUrl: 'https://static.hudongmiao.com/joymewMp/zyz/rocket1.png',
    }, {
        id: 2,
        gift: 'rocket2',
        name: '中号火箭',
        imgUrl: 'https://static.hudongmiao.com/joymewMp/zyz/rocket2.png',
    }, {
        id: 3,
        gift: 'rocket3',
        name: '大号火箭',
        imgUrl: 'https://static.hudongmiao.com/joymewMp/zyz/rocket3.png',
    }
];
const wishList = [
    '醉酒饱德，不胜感激',
    '美酒佳肴,不甚荣幸',
    '感谢招待,祝愿安康',
    '小小红包,感谢招待'
];
let requestLock = false;
Page({
    data: {
        gameStatus: 1, // 游戏状态(控制页面显示)
        myBoxesVisible: false,
        boxes: [],
        chooseBoxIds: [],
        remain: 3,
        money: 0,
        gift_show: { //当前显示的礼物
            id: 3,
            gift: 'rocket3',
            name: '大号火箭',
            imgUrl: 'https://static.hudongmiao.com/joymewMp/zyz/rocket3.png',
            price: 0,
        },
        userId: '',
        openId: '',
        name: '',
        headImg: '',
        luckyBoxes: [],
    },
    onLoad: function (options) {
        requestLock = false;
        this.setData({
            userId: options.userId,
            openId: options.openId,
            name: options.name,
            headImg: options.headImg,
        });
        getGameState(this.data.userId).then((res) => {
            if (res.success) {
                if (res.data.status === '1') {
                    this.setData({
                        gameStatus: 2,
                    });
                    this.getBoxes();
                } else if (res.data.status === '2') {
                    showWxToast('本轮开宝箱已经结束');
                    timeoutTask(() => {
                        wx.navigateBack();
                    }, 1500);
                }
            }
        })

    },
    onShow: function () {

    },
    onUnload: function () {
    },
    // 获取宝箱列表
    getBoxes: function () {
        getBoxesList().then((res) => {
            if (res.success) {
                const tmpLen = res.data.length;
                const tmpBoxes = [];
                for (let i = 0; i < tmpLen; i += 1) {
                    tmpBoxes.push({
                        id: res.data[i].eggId,
                        isBuyed: res.data[i].userId === '0' ? false : true,
                        isChoosed: false,
                        buyerId: res.data[i].userId,
                        num: BX[i].num,
                        left: BX[i].left,
                        top: BX[i].top,
                    });
                }
                this.setData({
                    boxes: tmpBoxes,
                    money: parseFloat(res.message),
                });
                this.setRemain();
                this.updateGift();
                console.log('宝箱列表:', this.data.boxes);
            } else {
                showWxToast('获取宝箱信息失败');
            }
        })
    },
    // 获取已经选择宝箱的数目
    getChoosedBoxesNum: function (isIncludeBuyed) {
        const boxes = this.data.boxes;
        const len = boxes.length;
        let tmpNum = 0;
        if (isIncludeBuyed) {
            for (let i = 0; i < len; i += 1) {
                if (boxes[i].isChoosed || boxes[i].buyerId === this.data.userId) {
                    tmpNum += 1;
                }
            }
        } else {
            for (let i = 0; i < len; i += 1) {
                if (boxes[i].isChoosed) {
                    tmpNum += 1;
                }
            }
        }
        return tmpNum;
    },
    // 获取已经选择的宝箱列表
    getChoosedBoxesList: function () {
        const boxes = this.data.boxes;
        const len = boxes.length;
        const tmpChoosedBoxes = [];
        for (let i = 0; i < len; i += 1) {
            if (boxes[i].isChoosed) {
                tmpChoosedBoxes.push(boxes[i]);
            }
        }
        return tmpChoosedBoxes;
    },
    // 设置还可以购买的宝箱个数(一共可购买三个)
    setRemain: function () {
        let tmpRemain = 0;
        const tmpLen = this.data.boxes.length;
        for (let i = 0; i < tmpLen; i += 1) {
            if (this.data.boxes[i].buyerId === this.data.userId) {
                tmpRemain += 1;
            }
        }
        this.setData({
            remain: tmpRemain,
        });
    },
    // 获取选择的宝箱数目时更新祝福列表
    updateGift: function () {
        const hasChoosedNum = this.getChoosedBoxesNum(false);
        this.boxesMapGift(hasChoosedNum);
    },
    // 祝福和已选择的宝箱数的映射
    boxesMapGift: function (choosedNum) {
        const tmpMoney = this.data.money;
        giftList[0].price = tmpMoney.toFixed(2);
        giftList[1].price = (tmpMoney * 2).toFixed(2);
        giftList[2].price = (tmpMoney * 3).toFixed(2);
        if (choosedNum == 3) {
            //选了3个宝箱<---> 大火箭
            this.setData({
                gift_show: giftList[2],
            })
        } else if (choosedNum == 2) {
            //选了2个宝箱<---> 中火箭
            this.setData({
                gift_show: giftList[1],
            })
        } else {
            //选了1个宝箱或者还没有选蛋<--->小火箭
            this.setData({
                gift_show: giftList[0],
            })
        }
    },
    enterGame: function () {
        getGameState(this.data.userId).then((res) => {
            console.log('***获取游戏状态***');
            console.log(res);
            if (res.success) {
                if (res.data.status === '0') {
                    showWxToast('请等待大屏开启游戏');
                } else if (res.data.status === '1') {
                    // 游戏进行中
                    this.getBoxes();
                    this.setData({
                        gameStatus: 2,
                    })
                } else if (res.data.status === '2') {
                    showWxToast('本轮开宝箱已经结束');
                    timeoutTask(() => {
                        wx.navigateBack();
                    }, 1500);
                } else {
                    showWxToast('请等待大屏开启游戏');
                }
            }
        }).catch((err) => {
            console.log(err);
        });
    },
    // 选择宝箱
    chooseBoxes: function (e) {
        const index = this.findBoxIndexByBoxId(e.currentTarget.dataset.id);
        const boxes = this.data.boxes;
        if (boxes[index].isBuyed) {
            showWxToast('这个宝箱已经被抢走啦');
            return;
        }
        // 如果选中 取消选中
        if (boxes[index].isChoosed) {
            boxes[index].isChoosed = false;
            this.setData({
                boxes,
            });
            this.updateGift();
            return;
        }
        // 最多3个宝箱 包括已经购买的
        const hasChoosedNum = this.getChoosedBoxesNum(true);
        if (hasChoosedNum >= 3) {
            showWxToast('最多只能选择三个宝箱哦');
            return;
        }
        if (!boxes[index].isChoosed) {
            boxes[index].isChoosed = true;
            this.setData({
                boxes,
            })
            this.updateGift();
        }
    },
    // 通过boxesId查找宝箱所在数组的索引
    findBoxIndexByBoxId: function (boxId) {
        let tmpIndex = -1;
        const tmpLen = this.data.boxes.length;
        for (let i = 0; i < tmpLen; i += 1) {
            if (this.data.boxes[i].id === boxId) {
                tmpIndex = i;
                break;
            }
        }
        return tmpIndex;
    },
    // 打开我的宝箱页面
    toMyBoxes: function () {
        this.getLuckyBoxes();
        this.setData({
            myBoxesVisible: true,
        });
    },
    // 打开宝箱购买页面
    toBuyBoxes: function () {
        this.setData({
            myBoxesVisible: false,
        });
    },
    // 买宝箱
    buy: function () {
        // 获取选中的宝箱
        const choosed = this.getChoosedBoxesList();
        if (choosed.length == 0) {
            showWxToast('请先选一个宝箱');
            return;
        }
        if (requestLock) {
            return;
        }
        requestLock = true;
        let choosedStr = choosed.map((item) => {
            return item.id;
        }).join(',');
        this.robBox(choosedStr, 0).then((res) => {
            console.log(res);
            if (res.code === 'success') {
                requestLock = false;
                if (res.resultList.length == 0) {
                    wx.showModal({
                        showCancel: false,
                        title: '温馨提示',
                        content: '很遗憾您选择的宝箱都被抢走了\r\n已退回至您的账户中',
                        confirmText: '确定',
                        success: () => {
                        }
                    });
                } else {
                    if (choosed.length > res.resultList.length) {
                        wx.showModal({
                            showCancel: false,
                            title: '温馨提示',
                            content: '恭喜您,成功抢到了' + res.resultList.length + '个宝箱！ \r\n 未抢到的宝箱，已退回至您的账户中',
                            confirmText: '查看宝箱',
                            success: () => {
                                this.getLuckyBoxes();
                                this.setData({
                                    myBoxesVisible: true,
                                });
                            }
                        })
                    } else {
                        wx.showModal({
                            showCancel: false,
                            title: '温馨提示',
                            content: '恭喜您,成功抢到了' + res.resultList.length + '个宝箱!',
                            confirmText: '查看宝箱',
                            success: () => {
                                this.getLuckyBoxes();
                                this.setData({
                                    myBoxesVisible: true,
                                });
                            }
                        })
                    }
                    console.log(res.resultList);
                    let tmpCode = '';
                    if (this.data.gift_show.id === 3) {
                        tmpCode = 7002;
                    } else if (this.data.gift_show.id === 2) {
                        tmpCode = 6002;
                    } else if (this.data.gift_show.id === 1) {
                        tmpCode = 5002;
                    }
                    let c = JSON.stringify({
                        code: tmpCode,
                        param: {
                            headImg: this.data.headImg,
                            nickname: this.data.name,
                            wish: wishList[getRandom(0, 4)],
                        }
                    });
                    // 发送广播
                    sendBroadCast({
                        c,
                    });
                    app.globalData.isH5NeedRefresh = true;
                }
                this.getBoxes();
            } else if (res.code === 'error3') {
                if (res.NeedMoney) {
                    // 调起支付
                    return this.recharge(res.NeedMoney);
                } else {
                    showWxToast('购买失败!');
                }
            } else if (res.code === 'error4') {
                    showWxToast('开宝箱已经结束!');
                    requestLock = false;
            } else {
                showWxToast('购买失败');
                requestLock = false;
            }
        }).catch((err) => {
            console.log(err);
        })
    },
    // 抢宝箱
    robBox: function (boxId, sort) {
        return new Promise((resolve, reject) => {
            showWxLoading('奋力争抢中...');
            robBox({
                boxIds: boxId,
                sort: 0,
            }).then((res) => {
                console.log(res);
                hideWxLoading();
                resolve(res);
            }).catch((err) => {
                console.log(err);
                reject(err);
                hideWxLoading();
                showWxToast('抢购失败!');
            })
        });
    },
    // 支付
    recharge: function (money) {
        return new Promise((resolve, reject) => {
            kbxRecharge({
                userId: this.data.userId,
                openid: this.data.openId,
                money,
            }).then((res) => {
                console.log(res);
                if (res.status === 'success') {
                    wxPay(res).then((res2) => {
                        console.log(res2);
                        resolve(res2);
                        showWxToast('充值成功!');
                        requestLock = false;
                        app.globalData.isH5NeedRefresh = true;
                        //充值完成 等待后台加嗨币逻辑完成后 去买宝箱
                        timeoutTask(() => {
                            this.buy();
                        }, 500);
                    }).catch((err) => {
                        console.log(err);
                        showWxToast('充值失败!');
                        requestLock = false;
                        reject(err);
                    })
                }
            }).catch((err) => {
                console.log(err);
                reject(err);
            })
        });
    },
    // 获取我的宝箱
    getLuckyBoxes: function () {
        getMyBoxes().then((res) => {
            console.log(res);
            if (res.success) {
                if (res.data && res.data.length > 0) {
                    const tmpBoxes = [];
                    const tmpLen = res.data.length;
                    for (let i = 0; i < tmpLen; i += 1) {
                        if (res.data[i].eggId) {
                            let tmpEggId = parseInt(res.data[i].eggId);
                            if (tmpEggId <= 3) {
                                res.data[i].num = `0${tmpEggId}`;
                            } else if (tmpEggId >= 4 && tmpEggId <= 8) {
                                res.data[i].num = `0${tmpEggId + 1}`;
                            } else if (tmpEggId >= 9 && tmpEggId <= 12) {
                                res.data[i].num = `${tmpEggId + 1}`;
                            } else {
                                res.data[i].num = `${tmpEggId + 2}`;
                            }
                            tmpBoxes.push(res.data[i]);
                        }
                    }
                    this.setData({
                        luckyBoxes: tmpBoxes
                    });
                }
            } else {
                showWxToast('获取宝箱信息失败!');
            }
        }).catch((err) => {
            console.log(err);
            showWxToast('获取宝箱信息失败!');
        })
    },
    toAgreement: function () {
        wx.navigateTo({
            url: '/pages/agreement/agreement'
        });
    },
});